//
//  HEEduVideoDetailsController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/12/17.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEEduVideoDetailsController.h"
#import "HEEduTitleCell.h"
#import "HEEduOperationCell.h"
#import "HEEduSelectionCell.h"
#import "HEEduVideoModel.h"

#import <ZFPlayer/ZFPlayer.h>
#import <ZFPlayer/ZFPlayerControlView.h>
#import <ZFPlayer/ZFAVPlayerManager.h>

#import "HEPlayerVideoCell.h"
#import "HEEduHeadVideoCell.h"
#import "LEEAlert.h"
#import "ShareView.h"
#import "HEShareCirlceViewController.h"

@interface HEEduVideoDetailsController ()<UITableViewDelegate, UITableViewDataSource, HEEduOperationCellDelegate, HEPlayerVideoCellDelegate, HEEduHeadVideoCellDelegate, HEEduSelectionVideoCellDelegate>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) GDFormModel *formModel;
@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) HEEduVideoModel   *details;

@property (nonatomic, strong) ZFPlayerController *player;
@property (nonatomic, strong) ZFPlayerControlView *controlView;

//@property (nonatomic, strong) AVPictureInPictureController *vc;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger pageSize;

@property (nonatomic, strong) HEVideoListModel   *videoModel;

/// 当前选择选集
@property (nonatomic, strong) HEVideoListModel *currentSelVideoModel;

/// 当前选中推荐
@property (nonatomic, strong) HEVideoListModel *currentRemVideoModel;

@property (nonatomic, assign) BOOL isSelection;

@end

@implementation HEEduVideoDetailsController

- (GDFormModel *)formModel {
    if (!_formModel) {
        _formModel = [[GDFormModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _pageNum = 1;
    _pageSize = 10;
    self.dataSource = @[].mutableCopy;
    
    self.zx_navBar.hidden = NO;
    self.title = @"健康视频";
    [self zx_setNavGradientBacFrom:KWhiteColor to:KWhiteColor];
    self.zx_navLineViewBackgroundColor = CSplitLineColor;
    self.zx_navTitleColor = KBlackColor;
    self.zx_backBtnImageName = @"back_black";
    self.zx_navStatusBarStyle = ZXNavStatusBarStyleDefault;
    
    [self initUI];
    
    [self initCell];
    
    KWeakSelf
    [self loadData:^(HEEduVideoModel *model) {
        weakSelf.pageNum = 1;
        
        // 设置默认播放选集
        weakSelf.currentSelVideoModel = self.details.video.firstObject;
        weakSelf.details.video.firstObject.isCurrentPlay = YES;
        
        [weakSelf playFirstVideo];
        [weakSelf loadRecommData];
    }];
    
    [self setupCellPlayer];
}
 
- (void)playFirstVideo {
    [self playAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] model: _details.video.firstObject];
}

- (void)initUI {
    
   _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight-ZXNavBarHeight) style:UITableViewStyleGrouped];
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, CGFLOAT_MIN)];
    _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, CGFLOAT_MIN)];
   _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
   _tableView.scrollsToTop = YES;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.estimatedRowHeight = 44;
   self.tableView.backgroundColor = KWhiteColor;
   self.tableView.delegate = self;
   self.tableView.dataSource = self;
   [self.view addSubview:self.tableView];
    
    KWeakSelf
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        weakSelf.pageNum += 1;
        weakSelf.isFromHeadRefresh = NO;
        [weakSelf loadRecommData];
    }];
}

- (void)setupCellPlayer {
    /// playerManager
    ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
//    ZFIJKPlayerManager *playerManager = [[ZFIJKPlayerManager alloc] init];
    
    /// player的tag值必须在cell里设置
    self.player = [ZFPlayerController playerWithScrollView:self.tableView playerManager:playerManager containerViewTag: 100];
    self.player.controlView = self.controlView;
    self.player.shouldAutoPlay = NO;
    /// 1.0是完全消失的时候
    self.player.playerDisapperaPercent = 1.0;

    @zf_weakify(self)
    self.player.orientationWillChange = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
        kAppDelegate.allowOrentitaionRotation = isFullScreen;
    };
     
    self.player.playerDidToEnd = ^(id  _Nonnull asset) {
        @zf_strongify(self)
        [self.controlView resetControlView];
        [self.player stopCurrentPlayingCell];
    };
    
    /// 停止的时候找出最合适的播放
    self.player.zf_scrollViewDidEndScrollingCallback = ^(NSIndexPath * _Nonnull indexPath) {
        @zf_strongify(self)
        if (!self.player.playingIndexPath) {
            [self playTheVideoAtIndexPath:indexPath];
        }
    };
  
    /// 以下设置滑出屏幕后不停止播放
    self.player.stopWhileNotVisible = NO;
    
    CGFloat margin = 20;
    CGFloat w = KScreenWidth/2;
    CGFloat h = w * 9/16;
    CGFloat x = KScreenWidth - w - margin;
    CGFloat y = KScreenHeight - h - margin;
    self.player.smallFloatView.frame = CGRectMake(x, y, w, h);
}
 
- (void)backClick {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)initCell {
   // 总段
   _sections = [NSMutableArray array];
    
    GDFiterCellModel *hModel = [GDFiterCellModel new];
    hModel.cellKlass = HEEduHeadVideoCell.class;
  
    GDFiterCellModel *titileModel = [GDFiterCellModel new];
    titileModel.cellKlass = HEEduTitleCell.class;
    
    GDFiterCellModel *operationModel = [GDFiterCellModel new];
    operationModel.cellKlass = HEEduOperationCell.class;
    
    GDFiterCellModel *selModel = [GDFiterCellModel new];
    selModel.cellKlass = HEEduSelectionCell.class;
    
    GDFiterCellModel *videoModel = [GDFiterCellModel new];
    videoModel.cellKlass = HEPlayerVideoCell.class;
    
    NSMutableArray *classArr = @[hModel, titileModel, operationModel, selModel, videoModel].mutableCopy;

   // 添加的时候注意顺序，暂未对顺序做处理
   [self.tableView mc_registerCellByFiterModels: classArr];
 
    NSMutableArray *sec1 = [NSMutableArray array];
    [sec1 addObject:hModel];
    [sec1 addObject:titileModel];
    [sec1 addObject:operationModel];
    [sec1 addObject:selModel];
    
    
    NSMutableArray *sec2 = [NSMutableArray array];
    [_sections addObject:sec1];
    [_sections addObject:sec2];

    [_tableView reloadData];
}

// 加载相关推荐数据
- (void)loadRecommData {
    
    HEPageRequest *req = [HEPageRequest new];
    req.pageNum = _pageNum;
    req.pageSize = _pageSize;
    [req addParmas: _currentSelVideoModel.tags key:@"tags"];
    
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KEduVideoRela parameters:req success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        
        NSArray <HEVideoListModel *>*arr = [HEVideoListModel mj_objectArrayWithKeyValuesArray:response.data];
        NSMutableArray *sec2 = self.sections.lastObject;
        
        if (self.isFromHeadRefresh) {
            [self removeAllRecomm];
        }

        [self.dataSource addObjectsFromArray:arr];
        
        for (HEVideoListModel *model in arr) {
            GDFiterCellModel *videoModel = [GDFiterCellModel new];
            videoModel.cellKlass = HEPlayerVideoCell.class;
            [sec2 addObject:videoModel];
        }
        [self.tableView reloadData];
        
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_footer endRefreshing];
    }];
}

// 加载视频详请
- (void)loadData:(void (^)(HEEduVideoModel *model))block {
    
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KEduVideoInfo parameters:@{@"id": [NSNumber numberWithInteger:_infoId]} success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        HEEduVideoModel *model = [HEEduVideoModel mj_objectWithKeyValues: response.data];
        self.details = model;
 
        [self.tableView reloadData];
        block(model);
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)saveSeeInfo:(HEVideoListModel *)model {
    NSMutableDictionary *params = @{}.mutableCopy;
     
    NSInteger sec = round(_player.currentTime);
    [params setValue:[NSNumber numberWithInteger:sec]  forKey:@"viewer_time"];
    [params setValue:[NSNumber numberWithInteger: model.id] forKey:@"video_id"];

    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KEduVideoSave parameters:params success:^(id  _Nonnull responseObject) {
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    // 保存上次播放的视频记录
    [self saveSeeInfo:_videoModel];}

#pragma mark - UIScrollViewDelegate 列表播放必须实现

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [scrollView zf_scrollViewDidEndDecelerating];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [scrollView zf_scrollViewDidEndDraggingWillDecelerate:decelerate];
}

- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView {
    [scrollView zf_scrollViewDidScrollToTop];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [scrollView zf_scrollViewDidScroll];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [scrollView zf_scrollViewWillBeginDragging];
}



#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
   return _sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   NSMutableArray *sec = _sections[section];
   return sec.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
    
    MCTableBaseCell *cell = (MCTableBaseCell *)[_tableView mc_dequeueReusableCellWithClassType:fiterModel.cellKlass];
    cell.proxyVC = self;
    
    switch (indexPath.section) {
        case 0:
        {
            if (indexPath.row == 0) {
                [cell configCellWithModel: _currentSelVideoModel indexPath:indexPath];
            }else {
                [cell configCellWithModel: _details indexPath:indexPath];
            }
        }
            break;
        case 1:
        {
            [cell configCellWithModel: self.dataSource[indexPath.row] indexPath:indexPath];

        }
            break;
        default:
            break;
    }
   
    
   return cell;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//  NSMutableArray *sec = _sections[indexPath.section];
//   GDFiterCellModel *fiterModel = sec[indexPath.row];
//
//    return [tableView fd_heightForCellWithIdentifier: NSStringFromClass(fiterModel.cellKlass) cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
////        [cell configCellWithModel: item];
//    }];
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 
  
}


#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section == 1) {
        return 50;

    }
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
 
    if (section == 1) {
        UIView *v = [[UIView alloc] init];
        
        UIView *lineView = [[UIView alloc] init];
        lineView.backgroundColor = CNavBgColor;
        [v addSubview:lineView];

        UILabel *titleLb = [UILabel new];
        titleLb.text = @"相关推荐";
        titleLb.font = DYBlodFont(17);
        titleLb.textColor = CNavLightBlackColor;
        [v addSubview:titleLb];

        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(titleLb);
            make.left.equalTo(v).offset(15);
            make.width.offset(4);
            make.height.offset(20);
        }];
        
        [titleLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo(v);
            make.left.equalTo(lineView.mas_right).offset(10);
            make.right.equalTo(v).offset(-15);
        }];
        return v;
    }
    return [UIView new];
}

#pragma mark - HEPlayerVideoCellDelegate 推荐视频
- (void)playTheVideoAtIndexPath:(NSIndexPath *)indexPath {
    
    HEVideoListModel *model = self.dataSource[indexPath.row];
    [self playAtIndexPath: indexPath model:model];
}

#pragma mark - HEEduHeadVideoCellDelegate 头部视频
- (void)headCellPlayTheVideoAtIndexPath:(NSIndexPath *)indexPath model:(nonnull HEVideoListModel *)model{
    // 上次播放视频 置为no
    _currentSelVideoModel.isCurrentPlay = NO;
    
    // 准备播放视频 置为YES
    model.isCurrentPlay = YES;

    // 保存上次播放的视频记录
    [self saveSeeInfo:_videoModel];
    
    _currentSelVideoModel = model;
    [self.tableView reloadData];
    [self playAtIndexPath: indexPath model:model];
}

#pragma mark - HEEduSelectionVideoCellDelegate  选集视频
- (void)playSelectionVideo:(HEVideoListModel *)model {
    
    // 上次播放视频 置为no
    _currentSelVideoModel.isCurrentPlay = NO;
    
    // 准备播放视频 置为YES
    model.isCurrentPlay = YES;

    // 保存上次播放的视频记录
    [self saveSeeInfo:_videoModel];

    _currentSelVideoModel = model;
    [self.tableView reloadData];
    [self playAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] model: model];
}

- (void)removeAllRecomm {
    [self.dataSource removeAllObjects];
    [(NSMutableArray *)self.sections.lastObject removeAllObjects];
}

- (void)playAtIndexPath:(NSIndexPath *)indexPath model:(HEVideoListModel *)model{
    
    _videoModel = model;
    
    [self.player playTheIndexPath:indexPath assetURL:[NSURL URLWithString:model.video_url]];
//    [self.player seekToTime:_videoModel.viewer_time completionHandler:^(BOOL finished) {
//            
//    }];
    [self.controlView showTitle: model.title
                 coverURLString: model.video_icon
                 fullScreenMode: ZFFullScreenModeLandscape];
}

#pragma mark - lazy load
- (ZFPlayerControlView *)controlView {
    if (!_controlView) {
        _controlView = [ZFPlayerControlView new];
        _controlView.fastViewAnimated = YES;
        _controlView.autoHiddenTimeInterval = 5;
        _controlView.autoFadeTimeInterval = 0.5;
        _controlView.prepareShowLoading = YES;
        _controlView.prepareShowControlView = NO;
    }
    return _controlView;
}

#pragma mark -
- (BOOL)prefersStatusBarHidden {
    return NO;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationNone;
}

- (BOOL)shouldAutorotate {
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

#pragma mark -
// 点赞
- (void)cellWithThumbupHandler {
    for (HEVideoListModel *item in self.details.video) {
        NSMutableDictionary *params =@{}.mutableCopy;
        [params setValue:[NSNumber numberWithInteger: item.id] forKey:@"video_id"];
        
        if ([@"1" isEqualToString: _currentSelVideoModel.thumbup]) {
            [params setValue:@"0" forKey:@"thumbup"];
        }else {
            [params setValue:@"1" forKey:@"thumbup"];
        }
        
        [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KEduVideoUpdate parameters:params success:^(id  _Nonnull responseObject) {
            HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];

            if (response.success) {
                
                for (HEVideoListModel *item in self.details.video) {
                    item.thumbup = params[@"thumbup"];
                }
                [self.tableView reloadData];
    //            [self loadData:^(HEEduVideoModel *model) {
    //            }];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
    }
}

// 收藏
- (void)cellWithCollectHandler {
    NSMutableDictionary *params = @{}.mutableCopy;
    [params setValue:[NSNumber numberWithInteger: _infoId] forKey:@"video_id"];
    
    NSString *url = @"";
    if(_details.collection > 0) {
        url = KEduVideoCancelCollection;
    }else {
        url = KEduVideoCollect;
    }

    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:url parameters:params success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            
            if ([url isEqualToString:KEduVideoCollect]) {
                self.details.collection = 1;
            }else {
                self.details.collection = 0;
            }
            
            [self.tableView reloadData];
//            [self loadData:^(HEEduVideoModel *model) {
//
//            }];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)cellWithShareHandler {
  
    // 初始化分享视图
    CGFloat width = CGRectGetHeight([[UIScreen mainScreen] bounds]) > CGRectGetWidth([[UIScreen mainScreen] bounds]) ? CGRectGetWidth([[UIScreen mainScreen] bounds]) - 20 : CGRectGetHeight([[UIScreen mainScreen] bounds]) - 20;
    
    NSArray *arr = @[
    @{@"title" : @"微信" , @"image" : @"infor_popshare_weixin_nor" , @"highlightedImage" : @"infor_popshare_weixin_pre" , @"type" : [NSNumber numberWithInteger:ShareTypeToWechat]} ,
    @{@"title" : @"微信朋友圈" , @"image" : @"infor_popshare_friends_nor" , @"highlightedImage" : @"infor_popshare_friends_pre" , @"type" : [NSNumber numberWithInteger:ShareTypeToWechatTimeline]},
//    @{@"title" : @"圈子" , @"image" : @"share_group_select" , @"highlightedImage" : @"share_group_select" , @"type" : [NSNumber numberWithInteger:ShareTypeToCircleRoom]}
    ];
    
    ShareView *shareView = [[ShareView alloc] initWithFrame:CGRectMake(0, 0, width, 0) InfoArray:arr MaxLineNumber:3 MaxSingleCount:3];
    
    KWeakSelf
    shareView.openShareBlock = ^(ShareType type){
        if (type == ShareTypeToWechat) {
            [self wxShare:WXSceneSession];
        }else if (type == ShareTypeToWechatTimeline) {
            [self wxShare:WXSceneTimeline];
        }else if (type == ShareTypeToCircleRoom) {
            
            HEMissonListModel *infoModel = [HEMissonListModel new];
            infoModel.id = weakSelf.currentSelVideoModel.id;
            infoModel.info_title = weakSelf.currentSelVideoModel.title;
            infoModel.information_brief = weakSelf.currentSelVideoModel.brief;
            infoModel.img_url = weakSelf.currentSelVideoModel.video_icon;
            infoModel.infoUrl = weakSelf.currentSelVideoModel.video_url;
            infoModel.isFromChatPage = _isFromChatPage;
 
            HEShareCirlceViewController *vc = [HEShareCirlceViewController new];
            vc.model = infoModel;
            vc.messageType = HEIMMessageTypeInfoVideo;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
    };
    
    [LEEAlert actionsheet].config
    .LeeAddCustomView(^(LEECustomView *custom) {
        
        custom.view = shareView;
        
        custom.positionType = LEECustomViewPositionTypeCenter;
    })
    .LeeItemInsets(UIEdgeInsetsMake(0, 0, 0, 0))
    .LeeAddAction(^(LEEAction *action) {
        
        action.type = LEEActionTypeDefault;
        
        action.title = @"取消";
        
        action.titleColor = [UIColor grayColor];
    })
    #ifdef __IPHONE_13_0
    .LeeUserInterfaceStyle(UIUserInterfaceStyleLight)
    #endif
    .LeeShow();
    
}

- (void)wxShare:(int)scene {

    
    UIImageView *view = [UIImageView new];

    KWeakSelf
    [view sd_setImageWithURL:[NSURL URLWithString:_currentSelVideoModel.video_icon] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = weakSelf.currentSelVideoModel.title;
        message.description = weakSelf.currentSelVideoModel.brief;
        [message setThumbImage: image];
        
        WXVideoObject *webpageObject = [WXVideoObject object];
        webpageObject.videoUrl = weakSelf.currentSelVideoModel.video_url;
        message.mediaObject = webpageObject;
        
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.message = message;
        // 微信好友
        req.scene = scene;
        
        //唤起微信
        [WXApi sendReq:req completion:^(BOOL success) {
            
        }];
    }];
}

@end
 


 
